package net.wicp.tams.plugin.task.git;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.eclipse.jgit.api.Git;

import net.wicp.tams.common.Result;
import net.wicp.tams.common.apiext.IOUtil;
import net.wicp.tams.common.apiext.yaml.YamlUtil;
import net.wicp.tams.common.others.GitUtil;
import net.wicp.tams.plugin.constant.Env;

/***
 * 把配置文件上传configserver中，支持环境变量 ： za.env=dev/test/pre/prd
 * 
 * @author zhoujunhui
 *
 */
@Mojo(name = "conf", requiresProject = true)
public class ConfigManager extends AbstractMojo {

	@Parameter(defaultValue = "${basedir}")
	private String basedir;

	@Parameter(defaultValue = "${project.artifactId}")
	private String projectname;

	@Parameter(defaultValue = "${project.groupId}")
	private String groupId;

	// 选择环境，默认为dev开发环境 test:测试 pre： 预发 prd ：生产
	@Parameter(property = "env", defaultValue = "dev", required = true)
	private Env env;

	// 配置文件的存放目录，默认的目录为/confserver，与env和projectname能定位到文件
	@Parameter(property = "dir", defaultValue = "configserver", required = true)
	private String dir;

	@Override
	public void execute() throws MojoExecutionException, MojoFailureException {
		if (env == null) {
			throw new MojoFailureException("环境只能设置[dev|test|pre|prd]");
		}
		getLog().info(String.format("--------------提交的环境为：[%s]---------------------------", env.name()));
		// 如果环境变量 svn.user 有值，且没有设置过值，就用环境变量 的值

		String filepath = IOUtil.mergeFolderAndFilePath(basedir, dir,
				String.format("%s/%s-%s.yml", env.name(), projectname, env));

		File userconf = new File(filepath);
		if (!userconf.exists()) {
			throw new MojoFailureException("不存在此配置文件：" + filepath);
		}
		Result ok = YamlUtil.isOk(filepath);
		if (ok.isSuc())
			getLog().info("----文件检查成功-----" + filepath);
		else
			throw new MojoFailureException("配置文件检查不通过：" + filepath);

		String homeDir = "/.tp/configserver";
		String workDirPath = System.getProperty("user.home");
		File globleDir = new File(String.format("%s/%s", workDirPath, homeDir));
		if (!globleDir.exists()) {
			try {
				FileUtils.forceMkdir(globleDir);
			} catch (IOException e) {
				throw new MojoExecutionException("create dir " + globleDir.getPath() + " error: ", e);
			}
		}
		File workDir = new File(globleDir, env.name());
		try {
			Git git = GitUtil.openOrClone(workDir.getPath(), env.getRepository(), env.getBranch(), env.getUser(),
					env.getPwd());
			getLog().info("-----打开或者克隆仓库成功-----");
			GitUtil.pull(git, env.getUser(), env.getPwd());
			File wcPath = new File(workDir, projectname);
			if (!wcPath.exists()) {
				wcPath.mkdir();
			}
			FileUtils.copyFileToDirectory(new File(filepath), wcPath);// .copyFile(new File(filepath), wcPath);
			GitUtil.add(git, projectname);
			GitUtil.commitNoAdd(git, "by git maven plugin");
			GitUtil.push(git, env.getBranch(), env.getUser(), env.getPwd());
			getLog().info("-----代码合并并且推送成功-----");
		} catch (Exception e) {
			throw new MojoExecutionException("git error: ", e);
		}
		getLog().info("-----提交成功-----" + filepath);
	}

}
